<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="gameId">ID:</label>
        <input type="text" id="gameId" v-model="gameId" required />
      </div>
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const gameId = ref('')
const username = ref('')
const router = useRouter()

async function handleLogin() {
  try {
    const response = await fetch(
      `${import.meta.env.VITE_API_BASE_URL}/api/users/add`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          gameId: gameId.value,
          username: username.value,
        }),
      }
    )

    const data = await response.json()  // 解析返回的JSON数据
    
    if (data.code === 200) {  // 根据code判断是否成功
      // 保存用户信息到localStorage
      localStorage.setItem('userInfo', JSON.stringify({
        gameId: gameId.value,
        username: username.value
      }));
      router.push({
        path: '/dashboard',
        query: {
          gameId: gameId.value,
          username: username.value
        }
      })
    } else {
      alert(data.msg || '登录失败')  // 使用服务器返回的错误信息
    }
  } catch (error) {
    console.error('登录错误:', error)
    alert('网络错误，请检查连接后重试')
  }
}
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
}

form {
  display: flex;
  flex-direction: column;
}

div {
  margin-bottom: 15px;
}

label {
  margin-bottom: 5px;
  color: #333;
}

input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100%;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

input[type="text"], input[type="password"] {
  padding-left: 2px;
  padding-right: 2px;
}
</style> 